06. Playing with Structs
Last Question
The last question asked you to identify potential errors in a snipped of code. The following lines end up having errors:
Error lines
Lines 17, 19, and 23 have errors.
Error Reasoning
Error #1
For the struct definitions and creation of the braves and freddie instances, there are no problems. But starting on line 17, we have issues. We cannot change the name of the braves because we declared it as a constant. If we declared braves with var instead of let, then this statement would be just fine.
Error #2
Line 19 is also invalid. We cannot change the hometown property because it is defined as a constant in the Athlete struct. And that makes sense. You can’t change your hometown.
Error #3
Line 23 is invalid even though it might not seem like it. Remember that myFavoriteTeam was set equal to a property that is of type Team, not of type String. Therefore, Line 23 is trying to set myFavoriteTeam to the wrong type. If instead we set myFavoriteTeam equal to a Team, then we would be fine. For example, we could create a Team instance on the fly like this.
Team Cap
Instead of just specifying the string "San Francisco Giants", it can be encapsulated into a Team.
Wrap Up
Or, we can store it into a variable or constant like this:
var myFavoriteTeam = freddie.currentTeam
var theGiants = Team(name: "San Francisco Giants", stadium: "AT&T Park")
myFavoriteTeam = theGiants
For the final exercise, open Writing Structs with Properties Exercises.playground from the Beginning iOS Playground Collection and complete the exercises contained within it.
Writing Structs with Properties Outro